import { useDataStore } from '@renderer/stores';
import { useEffect } from 'react';

export function useBookmark () {
  const setBookmarks = useDataStore(s => s.setBookmarks)

  useEffect(() => {
    getBookmarks()

    async function getBookmarks () {
      const data = await window.api.getChromeBookmarks()
      if (data && data.roots && data.roots.bookmark_bar) {
        const bookmarks = getBookmarkUrls(data.roots.bookmark_bar.children)
        setBookmarks(bookmarks)
      }
    }
    function getBookmarkUrls (
      list: (IBookmarkFolder | IBookmarkUrl)[],
      res: IBookmarkUrl[] = [],
    ) {
      return list.reduce<IBookmarkUrl[]>((acc, item) => {
        if (item.type === 'url') {
          acc.push(item)
        } else {
          getBookmarkUrls(item.children, acc)
        }
        return acc
      }, res)
    }
  }, [])
}
